<template>
  <div class="map-container">
    <div class="map-content">
      <!-- Loading 指示器 -->
      <div v-if="loading" class="loading-overlay">加载中...</div>
      <div id="map"></div>
    </div>
  </div>
</template>

<script setup>
// 导入 OpenLayers 库
import { onMounted, onBeforeUnmount, ref } from "vue";
import "ol/ol.css";
import { Map, View } from "ol";

import { ScaleLine } from "ol/control";

//导入标注点图层
import { vectorLayer, img_wLayer } from "./config/config.js";
import { lineLayerAll } from "./config/line-config.js";
const allLayers = [img_wLayer, vectorLayer, lineLayerAll]; // 包含其他层，如 img_wLayer
let map = null;
const loading = ref(false);
onMounted(async () => {
  loading.value = true;

  // 创建地图实例
  map = new Map({
    target: "map", // 将地图渲染到容器中
    layers: [
      ...allLayers, // 使用 img_wLayer 作为底图，放在其他图层前面
    ],
    view: new View({
      center: [120.5825, 30.0024], // 默认中心点（杭州的坐标）
      zoom: 8,
      projection: "EPSG:4326",
    }),
  });

  // 添加比例尺控制
  const scaleLineControl = new ScaleLine();
  map.addControl(scaleLineControl);
  // 手动更新地图大小
  map.updateSize();
  // 当地图加载完成时，隐藏 loading
  map.on("rendercomplete", () => {
    loading.value = false; // 地图渲染完成后，隐藏 loading
  });
});

onBeforeUnmount(() => {
  if (map) {
    map.setTarget(null); // 销毁地图实例
  }
});
</script>

<style scoped>
.map-container {
  position: relative;
  width: 100%;
  .map-content {
    z-index: 0;
    #map {
      height: 90vh;
      z-index: 1;
      border: none;
      cursor: move;
      background: #000;
    }
  }

  .map-tool {
    position: absolute;
    top: 10px;
    right: 10px;
    display: flex;
    flex-direction: column;
    gap: 8px;
    background: rgba(255, 255, 255, 0.8);
    padding: 8px;
    border-radius: 8px;
    box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.2);
    z-index: 10; /* 保证工具栏的按钮在地图上层 */
  }

  .map-tool-item {
    background-color: #007bff;
    color: white;
    border: none;
    padding: 6px 12px;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
    margin: 0;
    transition: background-color 0.3s;
    &:hover {
      background-color: #0056b3;
    }
  }

  .loading-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(255, 255, 255, 0.7);
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 20px;
    color: #333;
    z-index: 99; /* 保证 loading 层在地图上层 */
  }
}
</style>
